import { defineStore } from "pinia";
import router from "@/router";
import { useUserStore } from "./user";
import { staticMenuRouter } from "@/router/modules";
import {
  filterAsyncRouter,
  filterRoutesByRole,
  filterRoutesToMenus,
} from "@/router/helpers";
import { getRoutes } from "@/api/auth";

interface IRouteState {
  /** 权限路由的模式(static|dynamic) */
  routeMode: ImportMetaEnv["VITE_ROUTE_MODE"];
  /** 菜单渲染数据 */
  menus: App.Menu[];
  /** 缓存的路由 */
  cacheList: string[];
}

export const useRouteStore = defineStore({
  id: "route",
  state: (): IRouteState => ({
    routeMode: import.meta.env.VITE_ROUTE_MODE,
    menus: [],
    cacheList: [],
  }),
  getters: {},
  actions: {
    /** 初始化权限路由 */
    initRoute() {
      return new Promise((resolve) => {
        if (this.routeMode === "static") {
          this.initStaticRoute().then((res) => {
            if (res) {
              resolve(res);
            }
          });
        } else {
          this.initDynamicRoute();
        }
      });
    },
    /** 静态权限路由 */
    initStaticRoute() {
      return new Promise((resolve) => {
        /** 请求后端权限路由 **/
        const userStore = useUserStore();
        getRoutes().then((res) => {
          const routeData = JSON.parse(JSON.stringify(res.data));
          const asyncRoutes = filterAsyncRouter(routeData);
          const totalRoute = staticMenuRouter.concat(asyncRoutes);
          const routes = filterRoutesByRole(
            totalRoute,
            userStore.userInfo.roles
          );
          console.log(234, routes);
          routes.forEach((route) => {
            route.children?.length
              ? router.addRoute(route)
              : router.addRoute("root", route);
          });
          const menus = filterRoutesToMenus(routes);
          this.setMenus(menus);
          resolve(true);
        });
      });
    },
    /** 动态权限路由 */
    initDynamicRoute() {},
    /** 设置菜单 */
    setMenus(menus: App.Menu[]) {
      this.menus = menus;
    },
  },
});
